"""
Manage a menu which is a list of episodes.
"""
from .log import log
from .gui.form.header import SimpleHeader
from .gui.form.button import BackButton
from .gui import listscreen
from .gui.app import GuiApp
from .gui.list import BaseListItem
from .gui.list.textitem import BasicTextItem
from podcast import index
import play
import playscreen

def CreateEpisodesMenu(app, feed_id, current_song):
  # Create Episodes screen
  feed = index.GetFeed(feed_id)
  header_cb = lambda screen: SimpleHeader(screen, feed.title(),
      [BackButton(app, screen, 'Back', 'podcasts')])
  screen, episodes = listscreen.CreateListScreen(app, header_cb)

  def PlayEpisode(episode_id):
    def OnScreenChangeComplete():
      episodes.ActionDone()
    def OnTap():
      feed = index.GetFeed(feed_id)
      episode = feed.GetEpisode(episode_id)

      def Finished():
        """Called when this episode finishes playing."""
        feed.SetListened(episode),
        app.SetCurrentScreen("podcasts", GuiApp.ENTER_FROM_LEFT)

      if episode.filename():
        play_screen = playscreen.PlayScreen(app, current_song)
        play_screen.PlayEpisode(feed, episode, Finished, "episodes",
            OnScreenChangeComplete)
        return BaseListItem.ON_TAP_UNHIGHLIGHT_LATER
      else:
        # TODO: The file mysteriously disappeared!
        log("Episode", episode_id, "in feed", feed_id, "has filename", episode.filename(), "which is empty")
        return BaseListItem.ON_TAP_UNHIGHLIGHT_NOW
    return OnTap

  episode_list = []
  for episode_id in feed.GetEpisodeIDs():
    episode = feed.GetEpisode(episode_id)
    if episode.downloaded():
      episode_list.append(episode)

  # Sort so that newest episodes are at the top of the list.
  episode_list.sort()
  episode_list.reverse()
  for episode in episode_list:
    episodes.AddItem(BasicTextItem(app, str(episode.title()),
      PlayEpisode(episode.episode_id()), is_new=(not episode.listened())))

  app.AddScreen("episodes", screen)

